# 螺旋矩阵


from typing import List


class Solution:

    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:

        if len(matrix) == 0:
            return []
        
        # 确定边界范围
        l,  r, t, b, res = 0, len(matrix[0]) - 1, 0, len(matrix) - 1, [] 

        while True:

            for i in range(l, r + 1):
                res.append(matrix[t][i])
            t = t + 1
            if t > b: break

            for i in range(t, b + 1):
                res.append(matrix[i][r])
            r = r - 1
            if l > r:
                break

            for i in range(r, l - 1, -1):
                res.append(matrix[b][i])
            b = b - 1
            if t > b: break

            for i in range(b, t - 1, -1):
                res.append(matrix[i][l])
            l = l + 1
            if l > r: break

        return res

            
if __name__ == "__main__":

    a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    sol = Solution()

    res = sol.spiralOrder(a)
    print(res)


